import json
from multiprocessing import Process, Lock
import time
import random


# 查票
def get_goods(name):
    # 读文件
    with open('data/12306Server', 'r', encoding='utf-8') as f:
        dic = json.load(f)
    print(f'用户{name} >> 查询余票：{dic.get("goodsNum")}')
    return dic


# 买票
def buy_goods(name):
    # 读文件
    with open('data/12306Server', 'r', encoding='utf-8') as f:
        dic = json.load(f)
    # 模拟网络延迟
    time.sleep(random.randint(1, 3))
    if dic.get("goodsNum") > 0:
        dic["goodsNum"] -= 1
        with open('data/12306Server', 'w', encoding='utf-8') as f:
            json.dump(dic, f)
        print(f'用户{name} >> 购票成功')
    else:
        print(f"余票不足，{name}购票失败")


def user(name, mutex):
    get_goods(name)
    # 抢锁
    mutex.acquire()
    buy_goods(name)
    # 释放锁
    mutex.release()


if __name__ == '__main__':
    mutex = Lock()
    for i in range(1, 5):
        p = Process(target=user, args=(i, mutex))
        p.start()
